<?php

# Controller: Store

class Store extends Controller {

	function __construct() {
		parent::Controller();
		$this->load->model('Product_model');
		$this->load->model('Cart_model');
		$this->load->model('Customer_model');
		$this->load->model('Order_model');
		$this->load->model('System_model');
		$this->load->model('Category_model');
		$this->load->model('User_model');
		//$this->load->helper('ssl');
		//maintain_ssl(TRUE);
	}
	
	function index() {
		$data['products'] = $this->Product_model->get_features(); # Get product features
		$banner = $this->System_model->get_random_banner(); # Get random banner
		if ($banner) {
			$this->System_model->update_lru($banner['id']);
		} else { $banner = array('id' => '','name' => ''); }
		$data['banner'] = $banner;
		$data['page_title'] = "Online Store";
		$data['current_page'] = "Home";
		$this->load->view('common/header',$data);
		$this->load->view('store/main');
		$this->load->view('common/footer');
	}
	
	function newlayout() {
		$data['products'] = $this->Product_model->get_features(); # Get product features
		$banner = $this->System_model->get_random_banner(); # Get random banner
		if ($banner) {
			$this->System_model->update_lru($banner['id']);
		} else { $banner = array('id' => '','name' => ''); }
		$data['banner'] = $banner;
		$data['page_title'] = "Online Store";
		$this->load->view('common/header_new',$data);
		$this->load->view('common/leftbar_new');
		$this->load->view('store/main_new');
		$this->load->view('common/footer_new');
	}	
	
	# Count banner hit times and redirect to corrensponding link
	function redirect($banner_id="") {
		$banner = $this->System_model->get_banner($banner_id);
		if ($banner) {
			$hit = $banner['hit'] + 1;
			$this->System_model->update_banner($banner['id'],array('hit' => $hit));		
		} else { $banner = array('url' => '#'); }
		if ($banner['url'] == "http://") { $banner['url'] = '#'; }
		redirect($banner['url']);
	}
	
	# Grab the input data and logs to database for later uses, then redirect to results page
	function search() {
		if (!isset($_POST['keyword'])) { redirect('store'); }
		$keyword = stripslashes($_POST['keyword']);
		$keyword = str_replace("'","",$keyword);
		$keyword = str_replace('"','',$keyword);
		$data = array(
			'session_id' => $this->session->userdata('session_id'),
			'ip_address' => $_SERVER['REMOTE_ADDR'],
			'keyword' => strtolower($keyword)
		);
		$this->System_model->add_keyword($data);
		$this->session->set_userdata('keyword',$keyword);
		$keyword = str_replace(' ','-',$keyword);
		redirect('store/result/'.$keyword);
	}
	
	# Display search result
	function result($keywordquery="",$row=0) {
		$keyword = $this->session->userdata('keyword');
		$per_page = $this->session->userdata('per_page');
		$sort_type = $this->session->userdata('sort_type');
		if (!$per_page) { $per_page = 36; $this->session->set_userdata('per_page',$per_page); }
		
		$total = count($this->Product_model->search($keyword,0,true));
		$this->load->library('pagination');
		$config['base_url'] = base_url().'store/result/'.$keywordquery.'/';
		$config['total_rows'] = $total;
		$config['per_page'] = $per_page;
		$config['num_links'] = 4;
		$config['uri_segment'] = 4;
		$config['cur_tag_open'] = '&nbsp;<span class="active">';
		$config['cur_tag_close'] = '</span>';
		
		$this->pagination->initialize($config);
		$data['links'] = $this->pagination->create_links();
		$data['total'] = $total;
		$data['products'] = $this->Product_model->search_group($row,$per_page,$keyword,0,$sort_type,true);
				
		$data['title'] = 'Search Results for keyword "'.$keyword.'"';
		$data['page_title'] = "Product Search Result";
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		$this->load->view('store/category');
		$this->load->view('common/footer');
	}
	
	# Save the products display settings to session and redirect to products list page
	function reloadpage($category_id="",$sort_type=0,$per_page=36) {
		$this->session->set_userdata('sort_type',$sort_type);
		$this->session->set_userdata('per_page',$per_page);
		redirect('store/category/'.$category_id);
	}
	
	# Category page
	function category($category_id="",$row=0) {	
		$category = $this->Category_model->identify($category_id);
		if(!$category) { redirect('error/error_404'); }
		$per_page = $this->session->userdata('per_page');
		$sort_type = $this->session->userdata('sort_type');
		if (!$per_page) { $per_page = 36; $this->session->set_userdata('per_page',$per_page);}
		$total = count($this->Product_model->search('',$category_id,true));
		$this->load->library('pagination');
		$config['base_url'] = base_url().'store/category/'.$category_id.'/';
		$config['total_rows'] = $total;
		$config['per_page'] = $per_page;
		$config['num_links'] = 4;
		$config['uri_segment'] = 4;
		$config['cur_tag_open'] = '&nbsp;<span class="active">';
		$config['cur_tag_close'] = '</span>';
		
		
		$this->pagination->initialize($config);
		$data['links'] = $this->pagination->create_links();
		$data['total'] = $total;
		$data['products'] = $this->Product_model->search_group($row,$per_page,'',$category_id,$sort_type,true);
		if (empty($data['products']['min_stock'])){
			$data['products']['min_stock'] = '10';
		}
		$listitem=$this->coverlist($data['products']);
		$this->session->set_userdata("listitem",$listitem);
		
		$title = $category['title'];
		if ($category['parent_id'] > 0) {
			$parent_category = $this->Category_model->identify($category['parent_id']);
			$title = $parent_category['title'].' &raquo; '.$title;
		}	
		$data['title'] = $title;
		$data['page_title'] = $title;
		$data['current_page'] = $category_id;
		$data['categories'] = $this->Category_model->any();
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		$this->load->view('store/category');
		$this->load->view('common/footer');
	}
	function coverlist($list){		
		$a="";
		foreach($list as $l)
			$a.=$l['id'].":";
		return $a;
	}
	function getnext($id, $list){
		$i=0;
		$break=false;	
		$temp =split(":",$list);
		while($i<count($temp)&& !$break){			
			if($temp[$i]==$id)
				$break=true;
			$i++;
		}
		if(!empty($temp[$i])){
			redirect('store/product/'. $temp[$i]);
		}else
			redirect('store/product/'. $temp[$i-1]);
		
	}
	function getprevious($id,$list){
		$temp =split(":",$list);
		$i=count($temp)-1;		
		$break=false;			
		while($i>0&& !$break){			
			if($temp[$i]==$id)
				$break=true;
			$i--;
		}
		if(!empty($temp[$i]))
			redirect('store/product/'. $temp[$i]);
	}
	# Product details page
	function product($id="") {
		$product = $this->Product_model->identify($id);
		if(!$product) { redirect('error/error_404'); }
		else if($product['status'] ==0)
		{
			redirect('error/error_404');
		}
		$data['hero'] = $this->Product_model->get_hero($id);
		$data['photos'] = $this->Product_model->get_photos($id);
		$data['crosssales'] = $this->Product_model->get_crosssales($id);
		$data['attributes'] = $this->Product_model->get_attributes($id);
		if (empty($product['min_stock'])){
			$product['min_stock'] = '10';
		}
		$data['product'] = $product;
		$data['page_title'] = $product['title'];
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		$this->load->view('store/product');
		$this->load->view('common/footer');
	}
	
	# Tell friend function
	function tellfriend() {
		$message = sprintf("
<p>Hi %s,</p>
<p>Your friend (%s) has just sent you a link<br/>
%s <br/>
with a message: <br/>
%s <br/>
====================== <br/>
Sent from 7 Eleven Online Merchandise Store<br/>

		",$_POST['friend_name'],$_POST['your_name'],$_POST['current_url'],$_POST['your_message']);
		
		//load email content
		$data['content'] = $message;
		$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);			
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($_POST['friend_email']);
		$this->email->reply_to($_POST['your_email'],$_POST['your_name']);
		$this->email->subject('Your friend just sent you a link');
		$this->email->message($message);
		if ($this->email->send()) {
			print '<span class="success">Your message has been sent to your friend successfully!</span>';
		} else {
			print '<span class="error">Error! Message not sent!</span>';
		}
	}	
	
	# Add an item to shopping cart (AJAX function)
	function addtocart() {
		$session_id = $this->session->userdata('session_id');
		$product_id = $this->input->post('product_id',TRUE);
		$quantity = 0;
		if(isset($_POST['quantity']))
		{
		$quantity = $this->input->post('quantity',TRUE);
		}
		else
		{
			$quantity = 1;
		}
		$product = $this->Product_model->identify($product_id);
		
		$user = $this->session->userdata('7elevencloggedin');
		$this->checktimeout();
		if ($user['level'] == 4) 
		{
			if ($product['sale_price_trade'] > 0) { $price = $product['sale_price_trade']; }
			else { $price = $product['price_trade']; }
		} else {		
			if ($product['sale_price'] > 0) { $price = $product['sale_price']; }
			else { $price = $product['price']; }
		}
		
		$attributes = $this->Product_model->get_attributes($product_id);
		$str = '';	
		$temp_str = '';
		//$temp = array();
		//in single product page
		if(isset($_POST['attributes']))
		{
			/*
			$selected_attributes = explode('~',$_POST['attributes']);
		 //$s=explode(":",$_POST['attributes']);
		 //print_r($s);
		 for($i=0;$i<count($attributes);$i++) 
		 {
			if(!empty($_POST['attributes']))
			{
				$s=explode(":",$selected_attributes[$i]);
				
				$str .= $attributes[$i]['name'].':'.$s[1].'~';
			}
			else {
				$str .= $attributes[$i]['name'].':'.$attributes[$i]['options'][0].'~';
			}
		 }
		 */
		
		 $str =  $_POST['attributes'];
		 
		
		 //print_r(json_decode($str));
		}
		else
		{
		 $temp = array();
		 // in home page and category page
		  if($attributes != NULL)
		  {
			for($i=0;$i<count($attributes);$i++)
			{
				$options = $this->Product_model->get_attribute($attributes[$i]['id']);
				$temp = array(
				          $attributes[$i]['name'] => $options[0]
						  );			  
			}
		  }
		  if($product['multiplesize'] == 1)
	    	{
				
				$multiple_stock = json_decode($product['size'],true);
				foreach($multiple_stock as $key => $value)
				{
					if($multiple_stock[$key] > 0)
					{
			    	 $temp['Size'] = $key;
					 break;
					}
				}
			}
			$str = json_encode($temp, JSON_FORCE_OBJECT);
		}
		//echo $str;
		$data = array(
			'session_id' => $session_id,
			'product_id' => $product_id,
			'price' => $price,
			'quantity' => $quantity,
			'attributes' => $str
		);
		/*
		if($user['level']==4)
		{
			$status = $this->Cart_model->add($data);
			if ($status == -1) {
				print "You have already added this item to your shopping basket. You can add this item again if you change the product attribute such as colour. The quantity you would like to purchase can be modified at checkout or while viewing your shopping basket.";
			} else if ($status > 0) {
				print "You have successfully added $quantity products to your shopping basket";
			} else {
				print "There was an error when trying to add product to your cart. Please try again later!";
			}
		}
		*/
		$url=base_url()."contact";
		if($product['multiplesize'] == 0)
		{
			$status = $this->Cart_model->add_limited($data);
			if($status<=-2)
			{								
				//print "Sorry this item has low stock levels, so you just either lower the quantity or you still want to keep the amount you want to buy please contact us at sales@onlinemerchandise.com.au to enquiry about the availability, please be sure to let us know how many units you require. We will be in contact shortly.";
				print "Sorry this item has a low stock level. <br><br>

You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>

Please contact us at <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
			}
			else if ($status == -1) 
			{
				//print "You have already added this item to your shopping basket. You can add this item again if you change the product attribute such as colour. The quantity you would like to purchase can be modified at checkout or while viewing your shopping basket.";
				print "You have successfully added $quantity products to your shopping basket";
			} 
			else if ($status > 0) 
			{
				print "You have successfully added $quantity products to your shopping basket";
			} 
			else 
			{
				print "There was an error when trying to add product to your cart. Please try again later!";
			}
		}
		else if($product['multiplesize'] == 1)
		{
			
			// do quantity check for each size if multiple size is checked
			$temp_str = json_decode($str,true);
			$multiple_stock = json_decode($product['size'],true);
			$size = $temp_str['Size'];
			if($multiple_stock[$temp_str['Size']] < $quantity)
			{
				//print "Sorry this item has low stock level in the size $size, so you just either lower the quantity or you still want to keep the amount you want to buy please contact us at sales@onlinemerchandise.com.au to enquiry about the availability, please be sure to let us know how many units you require. We will be in contact shortly.";
				print "Sorry this item has a low stock level in the size $size. <br><br>

You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>

Please contact us at"." <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
			}
			else
			{
			  $status = $this->Cart_model->add_limited_special($data,$multiple_stock[$temp_str['Size']]);
			  if($status ==-2)
			  {		
//			     print "Sorry this item has low stock level in the size $size, so you just either lower the quantity or you still want to keep the amount you want to buy please contact us at sales@onlinemerchandise.com.au to enquiry about the availability, please be sure to let us know how many units you require. We will be in contact shortly.";
			     
print "Sorry this item has a low stock level in the size $size. <br><br>

You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>

Please contact us at"." <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
			  }
			  else if ($status == -1) 
			  {
				//print "You have already added this item to your shopping basket. You can add this item again if you change the product attribute such as colour. The quantity you would like to purchase can be modified at checkout or while viewing your shopping basket.";
				print "You have successfully added $quantity products to your shopping basket";
			  } 
			  else if ($status > 0) 
			  {
				print "You have successfully added $quantity products to your shopping basket";
			  } 
			  else 
			  {
				print "There was an error when trying to add product to your cart. Please try again later!";
			  }
			}
			
		}
		
	}
	
	# Update shopping cart (AJAX function)
	function updatecart() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		$quantity = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
			$quantity += $item['quantity'];			
		}
		if (count($cart) < 2) { $s1 = 'product'; } else { $s1 = 'products'; }
		//if ($quantity < 2) { $s2 = 'item'; } else { $s2 = 'items'; }
		printf('%01.2f',$total);
	}
	# Update number of items (AJAX function)
	function updatenumberitems() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		
		$quantity = 0;
		if(count($cart) > 0)
		{
			$quantity = count($cart);
		}
		print($quantity);
	}
	
	# Get sub total cost in shopping cart (AJAX function)	
	function subtotal() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		printf('%01.2f',$total);
	}
	
	# Shopping Cart page
	function cart() {
		$data['cart'] = $this->Cart_model->all($this->session->userdata('session_id'));
		$data['page_title'] = "Your Shopping Basket";
		$this->load->view('common/header',$data);
		
		$this->load->view('store/cart');
		$this->load->view('common/footer');
	}
	
	# Remove item from shopping cart (AJAX function)
	function removeitem() {
		$id = $_POST['id'];
		$this->Cart_model->delete($id);
	}
	
	# Update an item (including quantity, attributes)
	function updateitems() {
		$cart = $this->Cart_model->all($this->session->userdata('session_id'));
		foreach($cart as $item) 
		{
			$product = $this->Product_model->identify($item['product_id']);
			$attributes = $this->Product_model->get_attributes($product['id']);
			$str = '';
			$quantity = $_POST['quantity-'.$item['id']];
			
			$valid = true;
			$temp = array();
			$name = $product['title'];
			if($product['multiplesize'] == 1)
			
			{
				
				$multiple_stock = json_decode($product['size'],true);
				
				if($_POST['sizeproduct-'.$item['id']])
				{
					$size = $_POST['sizeproduct-'.$item['id']];
					if($multiple_stock[$_POST['sizeproduct-'.$item['id']]] < $quantity)
					{
						$valid = false;
						$url=base_url()."contact";
						//$message = "Sorry the item $name has low stock level in the size $size, so you just either lower the quantity or you still want to keep the amount you want to buy please contact us at sales@onlinemerchandise.com.au to enquiry about the availability, please be sure to let us know how many units you require. We will be in contact shortly.";
						$message=	"Sorry this item $name has a low stock level. <br><br> You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>
Please contact us at <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
						$this->session->set_flashdata('error_product_quantity',$message);
						
					}
					else
					{
						$temp['Size'] = $_POST['sizeproduct-'.$item['id']];
					
					}
				}
			}
			else
			{
				if($product['stock'] < $quantity)
				{
					$valid = false;
					$url=base_url()."contact";
					//$message = "Sorry the item $name has low stock level, so you just either lower the quantity or you still want to keep the amount you want to buy please contact us at sales@onlinemerchandise.com.au to enquiry about the availability, please be sure to let us know how many units you require. We will be in contact shortly.";
					$message=	"Sorry this item $name has a low stock level. <br><br> You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>
Please contact us at <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
						$this->session->set_flashdata('error_product_quantity',$message);
						
				}
			}
			for($i=0;$i<count($attributes);$i++) 
			{
				//$str = $attributes[$i]['name'].':'.$_POST['attribute-'.$item['id'].'-'.$i].'~';
			
			    $options = $this->Product_model->get_attribute($attributes[$i]['id']);
				/*$temp = array(
				 $attributes[$i]['name'] =>  $_POST['attribute-'.$item['id'].'-'.$i]
				 );*/
				
				$temp[$attributes[$i]['name']]=$_POST['attribute-'.$item['id'].'-'.$i];	
			}
			$str = json_encode($temp, JSON_FORCE_OBJECT);
			
			$data = array(
				'quantity' => $quantity,
				'attributes' => $str
			);
			if($valid)
			{
			$this->Cart_model->update($item['id'],$data);
			}
		}
		redirect('store/cart');
	}
	
	# Checkout page
	function checkout() {
		$cart = $this->Cart_model->all($this->session->userdata('session_id'));
		$tax = $this->System_model->get_tax(1);
		$user = $this->session->userdata('7elevencloggedin');
    //$user = 1; // user always logged in, for testing
    //echo $tax['included']; 
		//if($user['level']!=4) 		
		if($user['level']==4) /*raquel */
		if ($tax) {
			if ($tax['included']) {
				//echo 'in';
				$cart2 = array();
				foreach($cart as $item) {
					$price = money_format('%i',$item['price'] * 10/11);
					
					$item['price'] = $price;
					
					$cart2[] = $item;
				} 
				$cart = $cart2;
			} else {
				//echo 'out';
			}			
		}
		
		$data['tax']=$tax['included'];
		$data['cart'] = $cart;
		$data['page_title'] = "Checkout";
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');	
		
		if ($user) 
		{
			$data['countries'] = $this->System_model->get_shipping_countries();
			$data['customer'] = $this->Customer_model->identify($user['customer_id']);
			if($user['level'] == 4)
			{
				
				$this->session->set_userdata('redeem_open',false);
				$this->load->view('store/checkout',$data);
			}
			
		} 
		else 
		{
			redirect('store/trade');
			//$data['countries'] = $this->System_model->get_countries();
			//$this->load->view('store/customer',$data);
		}
		$this->load->view('common/footer');
	}
	
	function trade($status="") {
		$data['countries'] = $this->System_model->get_countries();
		$data['page_title'] = "Trade Customer";
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		if($status == "sent")
		{
			$this->load->view('store/tradesent');
		}
		else
		{
		$user = $this->session->userdata('7elevencloggedin');
			if ($user['level'] == 4) {
				redirect('store/checkout');
			}
			$this->load->view('store/trade');
		}
		$this->load->view('common/footer');
	}
	function checkemail($email) {
		//$email = $_POST['email'];
		$customer = $this->Customer_model->recognize($email);
		if ($customer) {
			print "Yes";
		} else {
			print "No";
		}
	}
	function checkusername() {
		$username = $_POST['username'];
		$user = $this->User_model->recognize($username);
		if ($user['username']!='') {
			print "Yes";
		} else {
			print "No";
		}
	}
	
	# Show order status
	function status($result="") {
		if(!$this->session->userdata('7elevencloggedin'))
		{
			redirect('store');
		}
		$data['result'] = $result;
		$data['page_title'] = "Order Status";
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		$this->load->view('store/status');
		$this->load->view('common/footer');
	}
	
	# After order success
	function pathway($user_id="",$order_id="") {
		$user = $this->User_model->id($user_id);
		$this->session->set_userdata('7elevencloggedin',$user);
		$this->session->set_userdata('order_id',$order_id);
		redirect('store/status/success');
	}
	
	# Check coupon code, return code (AJAX function)
	function checkcoupon() {
		$code = $_POST['code'];
		$coupon = $this->System_model->check_coupon_code($code);
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		
		if($total >= $coupon['condition'] && $total > 0) 
		{
			if($coupon['type'] == 1) { // Percentage
				$discount = $total * $coupon['value'] / 100;
				$s = '('.$coupon['value'].'%)';
			} else {
				$discount = $coupon['value'];
				$s = '($'.$coupon['value'].')';
			}
			$dis = sprintf('%s $%01.2f',$s,$discount);
		}
		
		$output = '';
		if($coupon) 
		{
			if($coupon['actived']) 
			{
				if($coupon['allowed_used_times'] == 0 || $coupon['actual_used_times'] < $coupon['allowed_used_times']) 
				{
					if($coupon['permanent'] == 1) 
					{
						if($total >= $coupon['condition'] && $total > 0) 
		                {
						   $this->addcoupon($code);	
						  //$output = "Ok";
						 
						}
						else
						{
							$output = "Err01";
						}
					}
					else 
					{
						if($this->System_model->check_coupon_period($code,$coupon['from_date'],$coupon['to_date']))
						{
							if($total >= $coupon['condition'] && $total > 0) 
		                    {
						      //$output = "Ok";
							  $this->addcoupon($code);
							  
						    }
						    else
						    {
							 $output = "Err01";
						     }
						} 
						else 
						{ 
						$output = "Err04"; 
						}
					}
				} 
				else 
				{ 
				$output = "Err03"; 
				}
			} 
			else 
			{ 
			 $output = "Err02"; 
			}
		} 
		else 
		{ 
		$output = "Err01";	
		}
		print $output;
	}
	
	# Add coupon code to the order and update total cost (AJAX function)
	function addcoupon($code) {
		//$code = $_POST['code'];		
		$coupon = $this->System_model->check_coupon_code($code);
						
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		$dis = '0.00';
		$discount=0;
		if($total >= $coupon['condition'] && $total > 0) 
		{
			if($coupon['type'] == 1) { // Percentage
				$discount = $total * $coupon['value'] / 100;
				$s = '('.$coupon['value'].'%)';
			} else {
				$discount = $coupon['value'];
				$s = '($'.$coupon['value'].')';
			}
			$dis = sprintf('%s $%01.2f',$s,$discount);
		}
		
		//$subtotal = sprintf('$%01.2f',$total - $discount);
		$extra = '';
		if($coupon['condition'] >0 )
		{
			$extra = '$'.$discount.' off total order price for orders over $'.$coupon['condition'].'';
		}
		$out = '
		<table cellpadding="0" cellspacing="0" border="0" width="432">
		  <tr>
		    <td>Price before discount</td>
			<td align="right">$'.$total.'</td>
	      </tr>
		  <tr>
			<td width="200"><div style="margin-top:4px"><p class="green">'.$coupon['name'].' Discount Applied</p><p>'.$extra.'</p></div></td><td valign="top" align="right"><div style="margin-top:4px">$'.$discount.' off</div></td>
	      </tr></table>';
		print $out;
	}
	/* Author : Raquel */
	# Check Redeem, return code (AJAX function)
	function checkredeem() {
		$id = $_POST['id'];
		$redeem = $this->System_model->check_redeem($id);
		$session_id = $this->session->userdata('session_id');
		// Check quantity items
		$cart = $this->Cart_model->check_redeem($session_id);
		$i=1;
		$out='';
		$discount=0;
		foreach($cart as $item) {
			if($item['count'] >= 7)
			{
				$data[$i]=$item['product_id'];
				$data2[$i]=$item['price'];
				$out=$out.$data[$i].' '.$data2[$i];
				$discount=$discount+$item['price'];
//				echo $out;
				$i++;

			}
		}		
		$output = '';
		$this->session->set_userdata('redeem',$discount);
		$this->session->set_userdata('redeem_open',false);
		//echo $this->session->userdata('redeem');
		
		
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		//printf('%01.2f',$total);
		
		if($redeem) 
		{
			$output = "Err01";	
		} 
		else
		{
			 //$this->addredeem($id);	
			$j=0;
			if($i>1)
			{
					$nettotal=$total-$discount;
					$gst=$nettotal/11;
					$nettotal2=$nettotal-$gst;
					$alltotal=$nettotal+$gst;
					//$this->session->set_userdata('alltotal',0);
					//$this->session->set_userdata('alltotal',$alltotal);
					$this->session->set_userdata('redeem_open',true);
					$output = '<table cellpadding="0" cellspacing="0" border="0" width="435"> ';
					$output= $output.'<tr><td><span style="font-size:13px;">Subtotal</span></td><td align="right" class="green" style="font-size:16px">';
					$output=$output.sprintf('$%01.2f',$total).'</td></tr>';
					$output= $output.'<tr><td><span style="font-size:13px;">Discount applied</span></td><td align="right" class="red" style="font-size:16px">';
					$output=$output.sprintf('-$%01.2f',$discount).'</td></tr>';
					$output= $output.'<tr><td colspan="2"><hr></td></tr>';
					$output= $output.'<tr><td><span style="font-size:13px;">Net Total</span></td><td align="right" class="green" style="font-size:16px">';
					$output=$output.sprintf('$%01.2f',$nettotal2).'</td></tr>';
					$output= $output.'<tr><td><span style="font-size:13px;">GST</span></td><td align="right" class="green" style="font-size:16px">';
					$output=$output.sprintf('$%01.2f',$gst).'</td></tr>';
					$output= $output.'<tr><td><span style="font-size:13px;">TOTAL</span></td><td align="right" class="green" style="font-size:16px">';
					$output=$output.sprintf('$%01.2f',$nettotal).'</td></tr>';
					$output = $output.'</table>';
					/*
					$output = $output.'<table cellpadding="0" cellspacing="0" border="0" width="300"> ';
					
					for($j=1;$j<$i;$j++) 
					{
						$product = $this->Product_model->identify($data[$j]);
						$output=$output.'<tr><td>'.to_short($product['title'],34).'</td><td> $ '.$data2[$j].'</td></tr>';
					}
					$output = $output.'</table> ';
					*/
				
			}
			else
			if ($i==1)
			{$output="Err02";}
		}
		print $output;
	}
	
	# Update the shipping methods, depends on the selected country (AJAX function)
	function updateshippingmethod() {
		$methods = $this->System_model->get_shippings_country($_POST['country_id']);
		$out = '<select id="method" onChange="updateshippingcost()" name="shipping_method">';
		foreach($methods as $method) {
			$out .= '<option value="'.$method['id'].'">'.$method['name'].'</option>';
		}
		$out .= '</select>';
		print $out;
	}
	
	# Update the shipping cost, depends on the selected shipping method (AJAX function)
	function updateshippingcost() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		
		if($_POST['code'] != "") {
			$coupon = $this->System_model->check_coupon_code($_POST['code']);
			if($total >= $coupon['condition'] && $total > 0) {
				if($coupon['type'] == 1) { // Percentage
					$discount = $total * $coupon['value'] / 100;					
				} else {
					$discount = $coupon['value'];					
				}
				$total = $total - $discount;
			}
		}
		
		$method = $this->System_model->get_shipping($_POST['method_id']);
		$cost = $method['price_value'];
		
		$conditions = $this->System_model->get_shipping_conditions($method['id']);
		foreach($conditions as $condition) {
			if ($total >= $condition['condition']) {
				$cost = $condition['price'];
			}
		}
		$cost = $cost/1.1;		
		$s = '';
		if ($method['price_type'] == 2) {
			$s = 'Flat rate ex gst';
		}
		printf('(%s) $%01.2f',$s,$cost);
	}
	
	# Get the tax, depends on selected country (AJAX function)
	function gettax() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}		
		$tax = $this->System_model->get_tax_country($_POST['country_id']);
		$user = $this->session->userdata('7elevencloggedin');
		if ($tax) { 
			if ($user['level'] != 4) {
				$method = $this->System_model->get_shipping($_POST['method_id']);
				$gst_of_shipping = $method['price_value']-$method['price_value']/1.1;
				$conditions = $this->System_model->get_shipping_conditions($method['id']);
				foreach($conditions as $condition) {
					if ($total >= $condition['condition']) {
						$gst_of_shipping = $condition['price']-$condition['price']/1.1;
					}
				}		
				if ($tax['included']) {
					printf('(%s%% %s) $%01.2f',$tax['value'],$tax['name'],$total + $gst_of_shipping- $total/(($tax['value']+100)/100)); 
				} else {
					printf('(%s%% %s) $%01.2f',$tax['value'],$tax['name'],$gst_of_shipping + $total*$tax['value']/100); 
				}
			}
			else
				printf('(%s%% %s) $%01.2f',$tax['value'],$tax['name'],$total*$tax['value']/100);
		}
		else { print 'No tax'; }
	}
	
	# Update the total cost (AJAX function)
	function totalprice() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		
		# Discount first
		if($_POST['code'] != "") {
			$coupon = $this->System_model->check_coupon_code($_POST['code']);
			if($total >= $coupon['condition'] && $total > 0) {
				if($coupon['type'] == 1) { // Percentage
					$discount = $total * $coupon['value'] / 100;					
				} else {
					$discount = $coupon['value'];					
				}
				$total = $total - $discount;
			}
		}
		/*
		# Tax second
		$tax = $this->System_model->get_tax_country($_POST['country_id']);
		if ($tax) { 
			if (!$tax['included']) { 
				$total = $total + $total * $tax['value']/100; 
			}
		}
		*/
		# Shipping last
		//$method = $this->System_model->get_shipping($_POST['method_id']);
		//$cost = $method['price_value'];
		/*
		$conditions = $this->System_model->get_shipping_conditions($method['id']);
		foreach($conditions as $condition) {
			if ($total >= $condition['condition']) {
				$cost = $condition['price'];
			}
		}
		*/
		$total = $total + $cost;
		//printf('$%01.2f',$total);
		$s=' ';
		printf('%s $%01.2f',$s,$total);
	}
	# Update the total cost (AJAX function)
	function totalprice_trade() {
		$session_id = $this->session->userdata('session_id');
		$cart = $this->Cart_model->all($session_id);
		$total = 0;
		foreach($cart as $item) {
			$total += $item['price']*$item['quantity'];
		}
		$total2=$total;
		# Discount first
		if($_POST['code'] != "") {
			$coupon = $this->System_model->check_coupon_code($_POST['code']);
			if($total >= $coupon['condition'] && $total > 0) {
				if($coupon['type'] == 1) { // Percentage
					$discount = $total * $coupon['value'] / 100;					
				} else {
					$discount = $coupon['value'];					
				}
				$total = $total - $discount;
			}
		}
		
		$carts = $this->Cart_model->check_redeem($session_id);
		$i=1;
		$out='';
		$discounts=0;
		foreach($carts as $items) {
			if($items['count'] >= 7)
			{
				$data[$i]=$items['product_id'];
				$data2[$i]=$items['price'];
				$out=$out.$data[$i].' '.$data2[$i];
				$discounts=$discounts+$items['price'];
				$i++;

			}
		}	
		/*
		$nettotal=$total2-$discounts;
		$gst=$nettotal/11;
		$nettotal2=$nettotal-$gst;
		$alltotal=$nettotal2+$gst;
*/
		$nettotal=$total2-$discounts;
		if ($this->session->userdata('redeem_open'))
		{$gst=$nettotal/11;
		$alltotal=$nettotal+$gst;	
	
		$total = $total - $discounts;
		
		}else{$gst=0;
		}
		
		
		$taxs = $this->System_model->get_tax(1);
		$tax=$taxs['included'];

		if($tax==1)
		{	
			//$total=$total+$gst;
			
			
			
		} 
		
		# Tax second
		//$tax = $this->System_model->get_tax_country($_POST['country_id']);
		/*
		if ($tax) { 
			//if (!$tax['included']) { 
				$total = $total + $total * $tax['value']/100; 
			//}
		}
		# Shipping last
		/*$method = $this->System_model->get_shipping($_POST['method_id']);
		$cost = $method['price_value'];
		
		$conditions = $this->System_model->get_shipping_conditions($method['id']);
		foreach($conditions as $condition) {
			if ($total >= $condition['condition']) {
				$cost = $condition['price'];
			}
		}
		$total = $total + $cost;
		*/
		//printf('%01.2f', $total);
		printf(' %01.2f',$total);
	}
	//order of trade customer
	function order_trade() {
		if (!isset($_POST['address'])) 
		{ 
		redirect('store/checkout'); 
		}		
		//$firstname = $this->input->post('firstname',true);
		//$lastname = $this->input->post('lastname',true);
		$address = $this->input->post('address',true);
		$suburb = $this->input->post('suburb',true);
		$state = $this->input->post('state',true);
		//$phone = $this->input->post('phone',true);
		//$email = $this->input->post('email',true);
		//$country = $this->System_model->get_country($_POST['country']);
		$postcode = $this->input->post('postcode',true);
		$msg = $this->input->post('msg',true);
		//$this->session->set_userdata("comment",$msg);
		/*
		$cardname = $_POST['cardname'];
		$cardtype = $_POST['cardtype'];
		$cardnumber = $_POST['cardnumber'];
		$expmonth = $_POST['expmonth'];
		$expyear = $_POST['expyear'];
		$cvv = $_POST['cvv'];*/
		$shipping_method = '0';//$_POST['shipping_method'];
		$shipping_cost = 0;
		
		# Calculate sub total
		$session_id = $this->session->userdata('session_id');
		$user = $this->session->userdata('7elevencloggedin');
		$customer_id = $user['customer_id'];
		$customer = $this->Customer_model->identify($customer_id);
		$cart = $this->Cart_model->all($session_id);
		if($cart == NULL)
		{
			redirect('store');
		}
		$subtotal = 0;
		$valid = true;
		
		foreach($cart as $item) 
		{
			$product = $this->Product_model->identify($item['product_id']);
			 $name = $product['title'];
			if($product['multiplesize'] == 0)
			{
			  if($product['stock'] < $item['quantity'])
			  {
				  $valid = false;
				  if($product['stock'] <= 0)
				  {
					  $keep = false;
				  }
				  else if($product['stock'] > 0)
				  {
					  $keep = true;
				  }
				  if($keep)
				  {
					  $newdata = array(
					                  'quantity' => $product['stock']
									  );
					  $this->Cart_model->update($item['id'],$newdata);
				  }
				  else
				  {
					  $this->Cart_model->delete($item['id']);
				  }
				  //$message = "Sorry the item $name has low stock level since it has been sold recently. Your shopping cart has been updated automatically to reflect a maximum stock purchased. Please contact sales@onlinemerchandise.com.au for any questions";
				  	$url=base_url()."contact";
				  $message=	"Sorry this item $name has a low stock level. <br><br> You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>
Please contact us at <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
				  $this->session->set_flashdata('error_product_quantity',$message);
			  }
			}
			else if($product['multiplesize'] == 1)
			{
				$multiple_stock = json_decode($product['size'],true);
				$attr = json_decode($item['attributes'],true);
				$size = $attr['Size'];
				if($multiple_stock[$attr['Size']] < $item['quantity'])
				{
					 $valid = false;
				  if($multiple_stock[$attr['Size']] <= 0)
				  {
					  $keep = false;
				  }
				  else if($multiple_stock[$attr['Size']] > 0)
				  {
					  $keep = true;
				  }
				  if($keep)
				  {
					  $newdata = array(
					                  'quantity' => $multiple_stock[$attr['Size']]
									  );
					  $this->Cart_model->update($item['id'],$newdata);
				  }
				  else
				  {
					  $this->Cart_model->delete($item['id']);
				  }
					 //$message = "Sorry the item $name has low stock level in the size $size since it has been sold recently. Your shopping cart has been updated automatically to reflect a maximum stock purchased. Please contact sales@onlinemerchandise.com.au for any questions";
				  	$url=base_url()."contact";
					 $message=	"Sorry this item $name has a low stock level in the size $size. <br><br> You can lower the quantity you wish to purchase and try add the product to your basket again. <br><br>
Please contact us at <a href='$url'> 24-7support@7eleven.com.au</a> to enquire about availability.";
				  $this->session->set_flashdata('error_product_quantity',$message);
				}
			}
			$subtotal += $item['quantity'] * $item['price'];
		}
		if(!$valid)
		{
			redirect('store/cart');
		}
		# Tax first
		// australia country id is 13
		$tax_ob = $this->System_model->get_tax_country(13);
		$tax = 0;
		if ($tax_ob) {
			/*if ($tax_ob['included']) {
				$tax = $subtotal - $subtotal / (1 + $tax_ob['value']/100);
				$subtotal = $subtotal - $tax;
			} else {*/
				$tax = $subtotal * ($tax_ob['value']/100);
			//}
		}
		$subtotal2 = $subtotal + $tax;
		# Discount second
		$discount = 0;
		if($_POST['coupon-code'] != "")
		 {
			$coupon = $this->System_model->check_coupon_code($_POST['coupon-code']);
			if($coupon)
			{
			 if($subtotal2 >= $coupon['condition'] && $subtotal > 0) 
			 {
				if($coupon['type'] == 1) { // Percentage
					$discount = $subtotal2 * $coupon['value'] / 100;					
				} else {
					$discount = $coupon['value'];					
				}
				$subtotal2 = $subtotal2 - $discount;
				 $data = array(
			         'actual_used_times' => $coupon['actual_used_times'] + 1
					 );
					 $this->System_model->update_coupon($coupon['id'],$data);
			 }
			
				
			}
			$coupon_codes=$_POST['coupon-code'];
		}
		
		#redeem
		$total = $subtotal2;
		if ($this->session->userdata('redeem_open'))
		{
			
			$carts = $this->Cart_model->check_redeem($session_id);
			$i=1;
			$out='';
			$discounts=0;
			foreach($carts as $items) {
				if($items['count'] >= 7)
				{
					$data[$i]=$items['product_id'];
					$data2[$i]=$items['price'];
					$out=$out.$data[$i].' '.$data2[$i];
					$discounts=$discounts+$items['price'];
					$i++;
	
				}
			}	
			$coupon_codes='Launch Offer';
			$discount=$discounts;
			$total = $total - $discounts;
			
			$data2= array(
				'customer_id' => $customer_id,
				'date' => date('Y-m-d H:i:s'),
				'status' => '1'
			);
			$redeem_id= $this->Cart_model->add_redeem($data2);
		}		
		# Shipping last
		//$method = $this->System_model->get_shipping($shipping_method);
		//$shipping_cost = $method['price_value'];
		
		//$conditions = $this->System_model->get_shipping_conditions($method['id']);
		//foreach($conditions as $condition) {
			//if ($subtotal >= $condition['condition']) {
				//$shipping_cost = $condition['price'];
			//}
		//}
		
		
		$data = array(
			'customer_id' => $customer_id,
			'session_id' => $session_id,
			'order_time' => date('Y-m-d H:i:s'),
			'subtotal' => $subtotal,
			'coupon_code' => $coupon_codes,
			'discount' => $discount,
			'tax' => $tax,
			'shipping_cost' => '',
			'shipping_method' => '',
			'total' => $total,
			'storeno' => $customer['storeno'],
			'storename' => $customer['storename'],
			'tradingname' => $customer['tradingname'],
			'address' => $address,
			'suburb' => $suburb,
			'state' => $state,
			'country' => 'Australia',
			'postcode' => $postcode,
			'message' => $msg,
			'cardname' => '0',
			'cardtype' => '0',
			'cardnumber' => "***",
			'expmonth' => '0',
			'expyear' => '0',
			'cvv' => '0'
		);
		$order_id = $this->Order_model->add($data);
		//dont check lowstock when customer is a trade
		$this->updatestock($order_id);
		//$total = money_format('%i',$total);
		//$total = str_replace('.','',$total); # Money in cent
		//$response = $this->process_eWay($order_id,$firstname,$lastname,$customer['email'],$address.','.$city.' '.$state,$postcode,$cardname,$cardnumber,$expmonth,$expyear,$cvv,$total);
		
		
		//if (strtolower($response['EWAYTRXNSTATUS']) == "true") {
			//$this->send_order_confirmation_trader($order_id);
			//$this->send_order_confirmation($order_id);
			//$this->send_order_notification($order_id);
			$this->Order_model->update($order_id,array('status' => 'successful','msg' => ''));
			$user = $this->session->userdata('7elevencloggedin');
			$this->send_order_notification($order_id);
			
			
			/*$message="try email";
			$this->load->library('email');
			$config['mailtype'] = 'html';
			$this->email->initialize($config);
			$this->email->from('asd@example.com');
			
			//$this->email->to('rseptiane@gmail.com');
			$emailo = $this->System_model->get_email('name','order');
			$email_o = json_decode($emailo['address'],true);
			if ($email_o) 
			{
				$this->email->to($email_o[0]);
				if(count($email_o) > 1)
				{
				 for($i=1;$i<count($email_o);$i++) 
				 {
					$this->email->cc($email_o[$i]);
				 }
				}
			} 
			else 
			{
				//$this->email->to('hieu@propagate.com.au');
				$this->email->to('raquel@propagate.com.au');
			}
			$this->email->subject('New Order @ 7 Eleven Online Merchandise Store');
			$this->email->message($message);
			$this->email->send();
			*/
			//$this->check_stockallproduct();
			$this->session->destroy();
			redirect('store/pathway/'.$user['id'].'/'.$order_id);
			
		/*} else if(strtolower($response['EWAYTRXNSTATUS']) == "false") {
			$this->Order_model->update($order_id,array('status' => 'failed','msg' => $response['EWAYTRXNERROR']));
			$this->session->set_userdata('response',$response['EWAYTRXNERROR']);
			redirect('store/status/failed');*/
		//}
		
			
	}
	function check_stockallproduct()
	{
		$products = $this->Product_model->all();
		$message="";/*
		foreach ($products as $product ) {
			if (product['multiplesize']==0 && product['status']==1)
			{
				if($product['stock'] <= $product['min_stock'])
				{
					$message="Product Name :".$product['title']."<br>";
					$message=$message."Stock left : ".$product['stock'];
				}
			}
			elseif(product['multiplesize']==0 && product['status']==1) 
			{
				$multiple_stock = json_decode($product['size'],true);
				//if($multiple_stock['XXXS']>0){
			//		if($multiple_stock['XXS']>0){
			}
		}*/
		
	}
	
	
	//send information to host for low amount of products
	function updatestock($order_id){
		$order = $this->Order_model->identify($order_id);
		$cart = $this->Cart_model->all($order['session_id']);	
		
		$message="<p>=====================================================</p>";
		$message.='<div style="width:490px"><div style="float:left; width:350px"><b>Product Name</b></div><div style="float:right; width: 100px"><b>Stock</b></div></div>';
		$message.="<p>=====================================================<br/></p>";
		$send_check=false;
		
		foreach($cart as $item) 
		{
			$product = $this->Product_model->identify($item['product_id']);
		  if($product['multiplesize'] == 0)
	      {
			$amount_in_stock=$product['stock'];
			//echo $product['min_stock'];
			$still_in_stock=$amount_in_stock - $item['quantity'];
			//if($still_in_stock<=1)
			if($still_in_stock<=$product['min_stock'])
			{
				$send_check=true;
				//$this->send_low_stock_notification($item['product_id'], $product['title'], $still_in_stock);
				$message.='<div style="width:500px"><div style="float:left; width:360px">'.$product["title"].'</div><div style="float:right; width: 100px">'.$still_in_stock.'</div></div>';
				
			}
			$temp=array(
					'stock' => $still_in_stock
			        );
			/*
			if($still_in_stock<=0){
				$temp=array(
					'stock' => $still_in_stock
				);
			}
			*/
			$this->Product_model->update($item['product_id'],$temp);
		  }
		  if($product['multiplesize'] == 1)
		  {
			  // applying stock update for multiple size rather than the product stock in general
			   
			   $multiple_stock = json_decode($product['size'],true);
			   $var = json_decode($item['attributes'],true);
			   $new = $multiple_stock[$var['Size']] -  $item['quantity'];
			    $multiple_stock[$var['Size']] = $new;
				//$message.=$item['attributes'].' '.$item['quantity'].' '.$new;
				if($new<=$product['min_stock'])
				{
				$send_check=true;
				//$this->send_low_stock_notification($item['product_id'], $product['title'], $still_in_stock);
				$message.='<div style="width:500px"><div style="float:left; width:360px">'.$product["title"].' '.$item['attributes'].'</div><div style="float:right; width: 100px">'.$new.'</div></div>';
				
				}
				
				$multiple_stock = json_encode($multiple_stock,JSON_FORCE_OBJECT);
				$temp=array(
					'size' => $multiple_stock
			        );
			   $this->Product_model->update($item['product_id'],$temp);
		  }
		}
		$message.="<p>=====================================================</p>";
		//$send_check=true;
		if($send_check)
		{
			$this->send_low_stock_notification($message);
		}
	}
	function send_low_stock_notification($message){
		$subject = 'Low Stock Notification @ 7 Eleven Online Merchandise Store';
			$message = sprintf("
<p>Dear Mr/Madam</p>

<p>Your stock is low in 7 Eleven Online Merchandise Store</p>
%s<br/>

The 7 Eleven Online Merchandise Store

			",$message);
			
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
			
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');	
		//$this->email->to('rseptiane@gmail.com');
		
		$emailo = $this->System_model->get_email('name','stock');
		$email_o = json_decode($emailo['address'],true);
		if($email_o) 
		{
			$this->email->to($email_o[0]);
			if(count($email_o) > 1)
			{
			 for($i=1;$i<count($email_o);$i++) 
			 {
				$this->email->cc($email_o[$i]);
			 }
			}
		} 
		else 
		{
			$this->email->to('hieu@propagate.com.au');
		}
				
		$this->email->subject($subject);
		$this->email->message($message);
		$this->email->send();
	}
	
	# Grab order information
	/*
	function order() 
	{
		if (!isset($_POST['firstname'])) { redirect('store/checkout'); }		
		$firstname = $_POST['firstname'];
		$lastname = $_POST['lastname'];
		$address = $_POST['address'];
		$city = $_POST['city'];
		$state = $_POST['state'];
		//$country = $this->System_model->get_country($_POST['country']);
		$postcode = $_POST['postcode'];
		$comment =$_POST['msg'];
		//store comment
		$this->session->set_userdata("comment",$comment);
		
		$cardname = $_POST['cardname'];		
		$cardtype = $_POST['cardtype'];
		$cardnumber = $_POST['cardnumber'];
		$expmonth = $_POST['expmonth'];
		$expyear = $_POST['expyear'];
		$cvv = $_POST['cvv'];
		$shipping_method = $_POST['shipping_method'];
		$shipping_cost = 0;
		
		# Calculate sub total
		$session_id = $this->session->userdata('session_id');
		$user = $this->session->userdata('7elevencloggedin');
		$customer_id = $user['customer_id'];
		$customer = $this->Customer_model->identify($customer_id);
		$cart = $this->Cart_model->all($session_id);
		$subtotal = 0;
		foreach($cart as $item) {
			$subtotal += $item['quantity'] * $item['price'];						
		}
		
		# Shipping last
		$method = $this->System_model->get_shipping($shipping_method);
		$gst_shipping = $method['price_value']-$method['price_value']/1.1;
		$shipping_cost = $method['price_value']/1.1;
		# Tax first
		$tax_ob = $this->System_model->get_tax_country($_POST['country']);
		$subtotal_temp=$subtotal;		
		if ($tax_ob) {
			if ($tax_ob['included']) {
				$tax = $subtotal - $subtotal / (1 + $tax_ob['value']/100);				
				$subtotal = $subtotal- $tax;				
				
			} else {
				$tax = $subtotal * ($tax_ob['value']/100);				
			}
		}
		
		$subtotal2 = $subtotal + $tax;
		# Discount second
		$discount = 0;
		if($_POST['coupon'] != "") {
			$coupon = $this->System_model->check_coupon_code($_POST['coupon']);
			if($subtotal2 >= $coupon['condition'] && $subtotal > 0) {
				if($coupon['type'] == 1) { // Percentage
					$discount = $subtotal2 * $coupon['value'] / 100;					
				} else {
					$discount = $coupon['value'];					
				}
				$subtotal2 = $subtotal2 - $discount;
			}
		}
		
		$check=false;
		$conditions = $this->System_model->get_shipping_conditions($method['id']);		
		foreach($conditions as $condition) {
			if ($subtotal2 >= $condition['condition']) {
				$shipping_cost = $condition['price']/1.1;
				$gst_shipping = $condition['price'] - $shipping_cost;				
			}
		}
		$tax = $tax + $gst_shipping;
		$total = $subtotal2 + $shipping_cost + $gst_shipping;
		
		$data = array(
			'customer_id' => $customer_id,
			'session_id' => $session_id,
			'order_time' => date('Y-m-d H:i:s'),
			'subtotal' => $subtotal,
			'coupon_code' => $_POST['coupon'],
			'discount' => $discount,
			'tax' => $tax,
			'shipping_cost' => $shipping_cost,
			'shipping_method' => $shipping_method,
			'total' => $total,
			'firstname' => $firstname,
			'lastname' => $lastname,
			'address' => $address,
			'city' => $city,
			'state' => $state,
			'country' => $country,
			'postcode' => $postcode,
			'email' => $customer['email'],
			'cardname' => $cardname,
			'cardtype' => $cardtype,
			'cardnumber' => "***".substr($cardnumber,12),
			'expmonth' => $expmonth,
			'expyear' => $expyear,
			'cvv' => $cvv
		);
		$order_id = $this->Order_model->add($data);		
		$total = money_format('%i',$total);
		$total = str_replace('.','',$total); # Money in cent
		$response = $this->process_eWay($order_id,$firstname,$lastname,$customer['email'],$address.','.$city.' '.$state,$postcode,$cardname,$cardnumber,$expmonth,$expyear,$cvv,$total);
		
		if (strtolower($response['EWAYTRXNSTATUS']) == "true") {	
			$ccinfo = sprintf('
Status: Success
First name: %s
Last name: %s
Address: %s
City: %s
State: %s
Country: %s
Postcode: %s
Email: %s

Card name: %s
Card type: %s
Card number: %s
Card Expiry: %s - %s
CVV: %s
',$firstname,$lastname,$address,$city,$state,$country,$postcode,$customer['email'],$cardname,$cardtype,$cardnumber,$expmonth,$expyear,$cvv);
			
				
			$this->send_order_confirmation_retail($order_id);
			$this->send_order_notification_retail($order_id);
			$this->updatestock($order_id);
			$this->Order_model->update($order_id,array('status' => 'successful','msg' => $response['EWAYTRXNERROR']));
			$user = $this->session->userdata('7elevencloggedin');
			
			$this->session->destroy();
			redirect('store/pathway/'.$user['id'].'/'.$order_id);
			
		} else if(strtolower($response['EWAYTRXNSTATUS']) == "false") {
		
			$this->Order_model->update($order_id,array('status' => 'failed','msg' => $response['EWAYTRXNERROR']));
			$this->session->set_userdata('response',$response['EWAYTRXNERROR']);
			redirect('store/status/failed');		
		}
	}
	*/
	/*
	# Send the credit card information to eWay for processing
	function process_eWay($order_id,$firstname,$lastname,$email,$address,$postcode,$cardname,$cardnumber,$expmonth,$expyear,$cvv,$total) {
		# Payment config
		//$eWAY_CustomerID = "87654321"; // eWAY Customer ID for test
		$eWAY_CustomerID = "18608064";
		$eWAY_PaymentMethod = 'REAL_TIME_CVN'; // payment gatway to use (REAL_TIME, REAL_TIME_CVN or GEO_IP_ANTI_FRAUD)
		$eWAY_UseLive = true; // true to use the live gateway
		
		$this->load->model('Eway_model');			
		$this->Eway_model->init($eWAY_CustomerID, $eWAY_PaymentMethod, $eWAY_UseLive);
		
		# Set the payment details
		$this->Eway_model->setTransactionData("TotalAmount", $total); //mandatory field
		$this->Eway_model->setTransactionData("CustomerFirstName", $firstname);
		$this->Eway_model->setTransactionData("CustomerLastName", $lastname);
		$this->Eway_model->setTransactionData("CustomerEmail", $email);
		$this->Eway_model->setTransactionData("CustomerAddress", $address);
		$this->Eway_model->setTransactionData("CustomerPostcode", $postcode);
		$this->Eway_model->setTransactionData("CustomerInvoiceDescription", "7 Eleven Online Merchandise Store");
		$this->Eway_model->setTransactionData("CustomerInvoiceRef", "INV".$order_id);
		$this->Eway_model->setTransactionData("CardHoldersName", $cardname); //mandatory field
		$this->Eway_model->setTransactionData("CardNumber", $cardnumber); //mandatory field
		$this->Eway_model->setTransactionData("CardExpiryMonth", $expmonth); //mandatory field
		$this->Eway_model->setTransactionData("CardExpiryYear", $expyear); //mandatory field
		$this->Eway_model->setTransactionData("TrxnNumber", "TRXN".$order_id);
		$this->Eway_model->setTransactionData("Option1", "");
		$this->Eway_model->setTransactionData("Option2", "");
		$this->Eway_model->setTransactionData("Option3", "");
		$this->Eway_model->setTransactionData("CVN", $cvv);
		$this->Eway_model->setCurlPreferences(CURLOPT_SSL_VERIFYPEER, 0); // Require for Windows hosting
						
		$ewayResponseFields = $this->Eway_model->doPayment();
		
			
		if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"])=="false") {
			#return false;
			/*$out = ''; #"Transaction Error: " . $ewayResponseFields["eWAYresponseText"] . "<br>\n";		
			foreach($ewayResponseFields as $key => $value)
				$out .= "\n<br>\$ewayResponseFields[\"$key\"] = $value";
			return $out;
			return $ewayResponseFields;
		}
		
		else if (strtolower($ewayResponseFields["EWAYTRXNSTATUS"])=="true") {
			#return true;
			/*$out = ''; #"Transaction Success: " . $ewayResponseFields["eWAYresponseText"]  . "<br>\n";
			foreach($ewayResponseFields as $key => $value)
				$out .= "\n<br>\$ewayResponseFields[\"$key\"] = $value";
			return $out;
			return $ewayResponseFields;
		}
		else {
			print "Error: An invalid response was recieved from the payment gateway.";
			return;
		}		
	}
	*/
	function send_order_confirmation($order_id) {
		$order = $this->Order_model->identify($order_id);
		$cart = $this->Cart_model->all($order['session_id']);
		$products_info = '';
		foreach($cart as $item) 
		{
			$product = $this->Product_model->identify($item['product_id']);
			//$attributes = json_decode($item['attributes'],true);
			$products_info .= sprintf("			
<p>%s x %s			$%01.2f</p>
<p>More details %s</p>",$item['quantity'],$product['title'],$item['quantity'] * $item['price'],$item['attributes']);
		}
		$order_id = sprintf('%04d',$order_id);
		$order_time = date('l dS F Y',strtotime($order['order_time']));
/*		$products_info .= sprintf("<p>
==========================================<br/>
SUB TOTAL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			 	$%01.2f<br/>
TAX&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;					$%01.2f<br/>
SHIPPING COST&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			$%01.2f<br/>
==========================================<br/>
TOTAL					$%01.2f<br/>",$order['subtotal'],$order['tax'],$order['shipping_cost'],$order['total']);*/
$products_info .= sprintf("<p>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>SUB TOTAL</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>SHIPPING COST</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>DISCOUNT</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>TAX</div><div style='float:right; width:100px'> $%01.2f</div></div>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>TOTAL</div><div style='float:right; width:100px'>					$%01.2f</div></div>",$order['subtotal'],$order['shipping_cost'],$order['discount'],$order['tax'],$order['total']);
		$message = sprintf("<p>
Dear %s,</p>

<p>Thank you for your order from 7 Eleven Online Merchandise Store</p>

<p>==========================================<br/>
Order Number: %s<br/>
Order Placed: %s<br/>
Delivery Address: %s, %s %s %s</p>
<p>
%s
<br/><br/>
Kind Regards,<br/>
7 Eleven Online Merchandise Store
		",$order['firstname'],$order_id,$order_time,$order['address'],$order['city'],$order['state'], $order['postcode'],$products_info);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
	
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);		
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($order['email']);
		$this->email->subject('Order Confirmation @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}	
	/*
	function send_order_confirmation_retail($order_id) {
		$order = $this->Order_model->identify($order_id);
		$cart = $this->Cart_model->all($order['session_id']);
		
		$products_info = '';
		foreach($cart as $item) {
			$product = $this->Product_model->identify($item['product_id']);
			$attributes = str_replace("~","-",$item['attributes']);
			$products_info .= sprintf("			
<p>%s x %s			$%01.2f</p>
<p>More details %s</p>",$item['quantity'],$product['title'],$item['quantity'] * $item['price'],$attributes);
		}
		$order_id = sprintf('%04d',$order_id);
		$order_time = date('l dS F Y',strtotime($order['order_time']));
		$products_info .= sprintf("<p>
==========================================<br/>
SUB TOTAL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			 	$%01.2f<br/>
TAX&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;					$%01.2f<br/>
SHIPPING COST&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			$%01.2f<br/>
==========================================<br/>
TOTAL					$%01.2f<br/>",$order['subtotal'],$order['tax'],$order['shipping_cost'],$order['total']);
$products_info .= sprintf("<p>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>SUB TOTAL</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>SHIPPING COST</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>DISCOUNT</div><div style='float:right; width:100px'> $%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>TAX</div><div style='float:right; width:100px'> $%01.2f</div></div>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>TOTAL</div><div style='float:right; width:100px'>					$%01.2f</div></div>",$order['subtotal'],$order['shipping_cost'],$order['discount'],$order['tax'], $order['total']);
		$message = sprintf("<p>
Dear %s,</p>

<p>Thank you for your order from 7 Eleven Online Merchandise Store</p>

<p>==========================================<br/>
Order Number: %s<br/>
Order Placed: %s<br/>
Delivery Address: %s, %s %s %s</p>
<p>
%s
<br/><br/>

		",$order['firstname'],$order_id,$order_time,$order['address'],$order['city'],$order['state'], $order['postcode'],$products_info);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);		
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($order['email']);
		
		$this->email->subject('Order Confirmation @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
*/
	function send_order_confirmation_trader($order_id) {
		$order = $this->Order_model->identify($order_id);				
		$message = sprintf("
<br/>
Hi %s<br/><br/>

Thank you for placing your order with 7 Eleven Online Merchandise Store, this email is to confirm we have received your order and it's being processed now. <br/><br/>

If you have a 30-day account with 7 Eleven Online Merchandise Store we will dispatch your order promptly.<br/><br/>

Should you have any questions please don't hesitate to contact me.<br/><br/>

Kind Regards,<br/>
7 Eleven Online Merchandise Store

		",$order['storename']);

		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';	
		$this->email->initialize($config);	
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($order['email']);
		
		$this->email->subject('Order Confirmation @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}	
	
	function send_order_notification($order_id) {
		$order = $this->Order_model->identify($order_id);
		$customer = $this->Customer_model->identify($order['customer_id']);
		//$comment = $this->session->userdata("comment");
		$cart = $this->Cart_model->all($order['session_id']);
		$products_info = '';
		foreach($cart as $item) {
			$product = $this->Product_model->identify($item['product_id']);			
			//$attributes = str_replace("~",".",$item['attributes']);
			$products_info .= sprintf("			
<p>%s (%s)		%s x $%01.2f = $%01.2f</p>
<p>More details %s</p>",$product['title'],$item['attributes'],$item['quantity'],$item['price'],$item['quantity'] * $item['price'],$item['attributes']);
		}
		$products_info .= sprintf("
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>SUB TOTAL</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>SHIPPING COST</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>DISCOUNT</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>TAX	</div><div style='float:right; width:100px'>			$%01.2f</div></div>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>TOTAL</div><div style='float:right; width:100px'>$%01.2f</div</div>",$order['subtotal'],$order['shipping_cost'],$order['discount'],$order['tax'],$order['total']);
		$message = sprintf("<p>
<b>Delivery Docket</b><br>
Website Order</p>

<p>You have received an order from your website for:<br/>
Order number: %s <br/>
%s</p>
<p style='margin-left:0px'><br/>
Delivery Details </p>
<p>
Store No: %s<br/>
Store Name: %s<br/>
Franchisee: %s<br/>
Address: %s<br/>
Suburb: %s<br/>
Postcode: %s<br/>
State: %s %s<br/>
<br/>
Message: <br/>
%s
<p>
This order was placed on %s</p><br/>

7 Eleven Online Merchandise Store
		",$order_id,$products_info,$order['storeno'],$order['storename'],$customer['franchisee'],$order['address'],$order['suburb'],$order['postcode'],$order['state'],$order['message'],$order['order_time'],"");
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		//echo $message;
		//echo $order['email'];
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
        
		$emailo = $this->System_model->get_email('name','order');
		$email_o = json_decode($emailo['address'],true);
		if ($email_o) 
		{
			$this->email->to($email_o[0]);
			if(count($email_o) > 1)
			{
			 for($i=1;$i<count($email_o);$i++) 
			 {
				$this->email->cc($email_o[$i]);
			 }
			}
		} 
		else 
		{
			$this->email->to('hieu@propagate.com.au');
			
		}
		//$this->email->to('');
		$this->email->subject('New Order @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
     /*
	function send_order_notification_retail($order_id) {
		$order = $this->Order_model->identify($order_id);
		$comment = $this->session->userdata("comment");
		$cart = $this->Cart_model->all($order['session_id']);
		$products_info = '';
		foreach($cart as $item) {
			$product = $this->Product_model->identify($item['product_id']);			
			$attributes = str_replace("~",".",$item['attributes']);
			$products_info .= sprintf("			
<p>%s (%s)		%s x $%01.2f = $%01.2f</p>
<p>More details %s</p>",$product['title'],$attributes,$item['quantity'],$item['price'],$item['quantity'] * $item['price'],$attributes);
		}
		$products_info .= sprintf("
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>SUB TOTAL</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>SHIPPING COST</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>DISCOUNT</div><div style='float:right; width:100px'>$%01.2f</div></div>
<div style='width:390px'><div style='float:left; width:196px'>TAX	</div><div style='float:right; width:100px'>			$%01.2f</div></div>
==========================================<br/>
<div style='width:390px'><div style='float:left; width:196px'>TOTAL</div><div style='float:right; width:100px'>$%01.2f</div</div>",$order['subtotal'],$order['shipping_cost'],$order['discount'],$order['tax'],$order['total']);
		$message = sprintf("<p>
Website Order</p>

<p>You have received an order from your website for:<br/>
Order number: %s <br/>
%s</p>
<p style='margin-left:0px'><br/>
Delivery Details </p>
<p>
%s %s<br/>
%s<br/>
%s, %s<br/>
%s %s<br/>
Email address: %s <br/>
<br/>
Comment: <br/>
%s
<p>
This order was placed on %s</p>
		",$order_id,$products_info,$order['firstname'],$order['lastname'],$order['address'],$order['city'],$order['state'],$order['country'],$order['postcode'],$order['email'],$comment,$order['order_time']);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);
		$this->email->from($order['email']);
		
		$email_o = $this->System_model->get_email('name','order');
		if ($email_o) {
			$this->email->to($email_o[0]['address']);
			for($i=1;$i<count($email_o);$i++) {
				$this->email->cc($email_o[$i]['address']);
			}
		} else {
			$this->email->to('hieu@propagate.com.au');
		}
		
		$this->email->subject('New Order @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}	
	
	function register() {
		$username = $_POST['username'];
		$password = $_POST['password'];
		$email = $_POST['email'];
		$firstname = $_POST['firstname'];
		$lastname = $_POST['lastname'];
		$address = $_POST['address'];
		$city = $_POST['city'];
		$state = $_POST['state'];
		$country = $_POST['country'];
		$postcode = $_POST['postcode'];
		$phone = $_POST['phone'];
	  if($email == '' || $address == '')
	  {
	  }
	  else
	  {
		$data = array(
		
			'email' => $email,
			'firstname' => $firstname,
			'lastname' => $lastname,
			'address' => $address,
			'city' => $city,
			'state' => $state,
			'country' => $country,
			'postcode' => $postcode,
			'phone' => $phone,
			'joined' => date('Y-m-d H:i:s')
		);
		$customer_id = $this->Customer_model->add($data);
		if ($customer_id) {
			$user = array(
				'customer_id' => $customer_id,
				'username' => $username,
				'password' => md5($password),
				'level' => 1
			);
			$user_id = $this->User_model->add($user);
			$user['id'] = $user_id;
			$this->send_welcome($user);
			$this->send_notify($user);
			$this->session->set_userdata('7elevencloggedin',$user);
		}
		redirect('store/checkout');
	  }
	}
	*/
	function traderegister() 
	{
		$email = $this->input->post('email',true);
		$username = $email;
		$storename = $this->input->post('storename',true);
		$tradename = $this->input->post('tradename',true);
		$firstname = $this->input->post('firstname',true);
		$lastname = $this->input->post('familyname',true);
		$password = $this->input->post('password',true);
		//$company = $_POST['company'];
		//$tradingas = $_POST['tradingas'];
		//$abn = $_POST['abn'];
		$phone= $_POST['phone'];
		$mobile = $_POST['mobile'];
		$address = $_POST['address'];
		$address2 = $_POST['address2'];
		$city = $_POST['city'];
		$state = $_POST['state'];
		//$country = $_POST['country'];
		$postcode = $_POST['postcode'];
		
		/*
		$businessyear = $_POST['businessyear'];
		$businesstypes = '';
		if (isset($_POST['businesstypes'])) {
			foreach($_POST['businesstypes'] as $type) {
				$businesstypes .= $type.'~';
			}
		}
		//$businesstypes=$_POST['businesstypes'];
		//$howdidyouhear = $_POST['howdidyouhear'];
		//$interests = '';
		//if (isset($_POST['interests'])) {
			//foreach($_POST['interests'] as $int) {
				//$interests .= $int.'~';
			}
		}
		*/
	 if($email == '' || $storename== '' || $address == '' || $phone == '')
	 {
		 $this->session->set_flashdata('signup_mes','Please fill in all the required fields'); 
		redirect('store/trade');
	 }
	 else
	 {
		$data = array(
			'email' => $email,
			'firstname' => $firstname,
			'lastname' => $lastname,
			'storename' => $storename,
			'tradename' => $tradename,
			'phone' => $phone,
			'address' => $address,
			'address2' => $address2,
			'city' => $city,
			'state' => $state,
			'postcode' => $postcode,
			'phone' => $phone,
			'mobile' => $mobile,
			'joined' => date('Y-m-d H:i:s')
		);
		$customer_id = $this->Customer_model->add($data);
		if ($customer_id) {
			$user = array(
				'customer_id' => $customer_id,
				'username' => $username,
				'password' => md5($password),
				'level' => 4
			);
			$user_id = $this->User_model->add($user);
			$user['id'] = $user_id;
			$this->send_welcome_trader($user);
			$this->send_notify_trader($user);
		}
		redirect('store/trade/sent');
	 }
	 
	  
	}
	/*
	function validate() {
		if (!isset($_POST['username']) || !isset($_POST['password'])) { redirect('store/checkout'); }
		$user = $this->User_model->validate(array('username' => $_POST['username'], 'password' => $_POST['password']));
		if ($user && $user['level'] == 1) { $this->session->set_userdata('7elevencloggedin',$user); }
		else { $this->session->set_flashdata('error_login',true); }
		redirect('store/checkout');
	}
	*/
	
	function validatetrade_new() {
		if (!isset($_POST['storeno'])) { redirect('store/trade'); }
		/*
		$data = array(
			    'username' => $this->input->post('username',true), 
				'password' => $this->input->post('password-login',true)
				);*/
		$data = array(
			    'storeno' => $this->input->post('storeno',true)
				);
		$user = $this->User_model->validate_frontend_new($data);
		
		if ($user != NULL && $user['level'] == 4) 
		{ 
		  if($user['activated'])
		  {
		    		
		    	
				
				
		    //$this->session->set_userdata('7elevencloggedin',$user);
		    //redirect('content/welcome');
		    //$this->session->set_flashdata('error_login','Your password is wrong');
			if(isset($_POST['password-login']))
			{
					
				if($user['password']=="")
		    	{
		    			
					if( $_POST['password-login']=="changeme"){		
		    		$this->session->set_userdata('storeno_id',$user['customer_id']);
					$this->session->set_userdata('7elevencloggedin',$user);	
		    		redirect('store/resetpassword');
					}
					else {
						$this->session->set_flashdata('error_login','Sorry no such password exists in our system please try again or contact support via the contact section');		
					}
	
					 
		    	}
				else
				{
					$data2=array(
						'password' => md5($_POST['password-login']),
						'customer_id' => $user['customer_id']
					);
			    	$pass = $this->User_model->check_password($data2);
					//echo count($pass);
					if(count($pass)==0)
					{
						$this->session->set_flashdata('error_login','Your password is wrong');
					}
					else {
						//$this->session->set_flashdata('error_login','Your password is right');
						 $this->session->set_userdata('7elevencloggedin',$user);
					}
					}
			}
			
			
			
		  }
		  else
		  {
		  $this->session->set_flashdata('error_login','Your franchise account is not active yet. Your details have been sent to our office for evaluation and we will be in contact soon.');
		  }
		  
		}
		else 
		{ 
		  $this->session->set_flashdata('error_login','Wrong store no. Please try again!');
		  //redirect('store/trade');
		 }	
		 redirect('store/trade');	
	}
	
	function resetpassword()
	{
			
		$data['countries'] = $this->System_model->get_countries();
		$data['page_title'] = "Trade Customer";
		$this->load->view('common/header',$data);
		//$this->load->view('common/leftbar');
		/*
		if($status == "sent")
		{
			$this->load->view('store/tradesent');
		}
		else
		{
		
		$user = $this->session->userdata('7elevencloggedin');
			if ($user['level'] == 4) {
				redirect('store/checkout');
			}
			$this->load->view('store/resetpassword');
		}
		*/
		$this->load->view('store/resetpassword');
		$this->load->view('common/footer');	
		
	}
	function new_reset_password()
	{
		if (!isset($_POST['reset'])) { redirect('store/trade'); }
		$password=$this->input->post('reset',true);
		$data = array(
			    'password' => md5($password)
				);
		$id=$this->session->userdata('storeno_id');
		if ($this->User_model->update_password_customer($data,$id))
		{
			redirect('store/trade');
		}
		else
		{
				$this->session->set_flashdata('error_update','Please try again!');	
				redirect('store/resetpassword');	
		}
		
	}
	function validatetrade() {
		if (!isset($_POST['storeno'])) { redirect('store/trade'); }
		/*
		$data = array(
			    'username' => $this->input->post('username',true), 
				'password' => $this->input->post('password-login',true)
				);*/
		$data = array(
			    'storeno' => $this->input->post('storeno',true)
				);
		$user = $this->User_model->validate_frontend($data);
		if ($user != NULL && $user['level'] == 4) 
		{ 
		  if($user['activated'])
		  {
		   $this->session->set_userdata('7elevencloggedin',$user);
		   //redirect('content/welcome'); 
		  }
		  else
		  {
		  $this->session->set_flashdata('error_login','Your franchise account is not active yet. Your details have been sent to our office for evaluation and we will be in contact soon.');
		  }
		  
		}
		else 
		{ 
		  $this->session->set_flashdata('error_login','Wrong store no. Please try again!');
		  //redirect('store/trade');
		 }	
		 redirect('store/trade');	
	}
	function checktimeout(){
		$user = $this->session->userdata('7elevencloggedin');
		if(count($user)>0){			
		}else{
			redirect('store');
		}
	}
	/*
	function send_welcome($user) {
		$customer = $this->Customer_model->identify($user['customer_id']);
		$message = sprintf("
<br/>
Hi %s<br/><br/>

Thank you for becoming a member of 7 Eleven Online Merchandise Store<br/><br/>

You are now able to sign in and purchase products at your convenience.<br/><br/>

We hope you enjoy your shopping experience with us.<br/><br/>

Kind Regards,<br/><br/>
7 Eleven Online Merchandise Store

		",$customer['firstname']);
	
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';	
		$this->email->initialize($config);
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($customer['email']);
		$this->email->subject('Welcome to 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
	*/
	function send_welcome_trader($user) {
		$customer = $this->Customer_model->identify($user['customer_id']);
		$message = sprintf("
<p>Hi %s</p>

<p>Thank you for your application to become a 7 Eleven Online Merchandise Store member.<br/>

Your details have been sent to our office for evaluation and we will be in contact soon.</p>

<p>Warm Regards,</p>

<p>7 Eleven Online Merchandise Store</p>

		",$customer['firstname']);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';	
		$this->email->initialize($config);
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($customer['email']);
		$this->email->subject('Welcome to 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
	function send_notify_trader($user) {
		$customer = $this->Customer_model->identify($user['customer_id']);
		/*
		$types = explode('~',$customer['businesstypes']);
		$businesstypes = '';
		for($i=0;$i<count($types)-1;$i++) {
			$businesstypes .= sprintf("
%s",$types[$i]);
		}
		$ints = explode('~',$customer['howdidyouhear']);
		$interests = '';
		for($i=0;$i<count($ints)-1;$i++) {
			$interests .= sprintf("
%s",$ints[$i]);
		}
		*/
		$message = sprintf("

<p>A new franchise has signed up to 7 Eleven Online Merchandise Store. His/her details are:</p>

<p>Customer ID: %s<br/>
***************************<br/>

First name: %s<br/>
Family name: %s<br/>
Email Address: %s<br/>
Username: %s<br/>
Store Name: %s<br/>
Trading Name: %s<br/>
***************************<br/>

Address 1: %s<br/>
Address 2: %s<br/>
Suburb: %s<br/>
State: %s<br/>
Postcode: %s<br/>
Phone: %s<br/>
Mobile: %s<br/>
</p>",$customer['id'],$customer['firstname'],$customer['lastname'],$customer['email'],$user['username'],$customer['storename'],$customer['tradename'],$customer['address'],$customer['address2'],$customer['city'],$customer['state'],$customer['postcode'],$customer['phone'],$customer['mobile']);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
			
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);		
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		
		$emailt = $this->System_model->get_email('name','trade');
		$email_t = json_decode($emailt['address'],true);
		if ($email_t) 
		{
			$this->email->to($email_t[0]);
			if(count($email_t) > 1)
			{
			 for($i=1;$i<count($email_t);$i++) 
			 {
				$this->email->cc($email_t[$i]);
			 }
			}
		} else {
			$this->email->to('hieu@propagate.com.au');
		}
		
		$this->email->subject('New Franchise Signup @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
	/*
	function send_notify($user) {
		$customer = $this->Customer_model->identify($user['customer_id']);
		$message = sprintf("

<p>A new franchise has signed up to 7 Eleven Online Merchandise Store. His/her details are:</p>

<p>Customer ID: %s<br/>
Email: %s<br/>
Username: %s<br/>

First name: %s<br/>
Last name: %s<br/>
Address: %s<br/>
City: %s<br/>
State: %s<br/>
Country: %s<br/>
Postcode: %s<br/>
Telephone: %s</p>

		",$customer['id'],$customer['email'],$user['username'],$customer['firstname'],$customer['lastname'],$customer['address'],$customer['city'],$customer['state'],$customer['country'],$customer['postcode'],$customer['phone']);
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);		
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$emails = $this->System_model->get_email('name','signup');
		$email_s = json_decode($emails['address'],true);
		if($email_s) 
		{
			$this->email->to($email_s[0]);
			if(count($email_s) > 1)
			{
			 for($i=1;$i<count($email_s);$i++) 
			 {
				$this->email->cc($email_s[$i]);
			 }
			}
		} 
		else 
		{
			$this->email->to('hieu@propagate.com.au');
		}
		
		$this->email->subject('New Customer Signup at 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
	}
	*/
	function forgot() {
		$msg = '';
		if(isset($_POST['username'])) 
		{
			$customer = $this->Customer_model->recognize($_POST['username']);
			$user = $this->User_model->recognize($_POST['username']);
			if ($customer || $user) 
			{
				if($user['activated'] && $user['level'] == 4) 
				{
					$this->send_password($customer);
					$msg = '<p class="green">Your login details has been sent to your email address!</span>';
				} 
				else
				{
					//$customer = $this->Customer_model->identify($user['customer_id']);
					//if ($customer) {
						//$this->send_password($customer);
						$msg = '<p class="error">Your franchise account is not active yet. Your details have been sent to our office for evaluation and we will be in contact soon.</p>';
					//}
				}				
			} 
			else 
			{
				$msg = '<p class="error">Username / Email address is not found in the system!</span>';
			}
		}
		$data['msg'] = $msg;
		$this->load->view('store/forgot',$data);
	}
	
	function send_password($customer) {
		# Generate new random password
		$this->load->helper('string');
		$password = random_string('alnum', 8);
		$user = $this->User_model->customer($customer['id']);
		$message = sprintf("

<p>Dear %s %s</p>

<p>As requested your password has been reset. Your username and new password is noted below:</p>

<p>Username/Email: %s<br/>
Password: %s</p>
<p>
Please proceed to the website link below to commence shopping.<br/>
%s</p>


		",$customer['firstname'],$customer['lastname'],$user['username'],$password,base_url());
		
		//load email content
		//$data['content'] = $message;
		//$message = $this->load->view('email_template',$data, TRUE);
		
		$this->User_model->update($user['id'],array('password' => md5($password)));
		$this->load->library('email');
		$config['mailtype'] = 'html';
		$this->email->initialize($config);	
		$this->email->from('noreply@onlinemerchandise.com.au','7 Eleven Online Merchandise Store');
		$this->email->to($customer['email']);
		
		$this->email->subject('Your new password @ 7 Eleven Online Merchandise Store');
		$this->email->message($message);
		$this->email->send();
		//return $password;
	}
		
	function logout() {
		$this->session->destroy();
		redirect('store');
	}
	function export_orders_cron()
	{
		$orders = $this->Order_model->get_orders_export();
		$csvdir = '/home/odessa/public_html/7-11/beta/exportcsv/';
		$strip = array("\r\n", "\n", "\r", ",");
		$this->load->model('Cart_model');
		$this->load->model('Product_model');
	  foreach($orders as $order)
	  {
			 
		  $csvname = '7Eleven_'.$order['id'].'_'.date('Ymd');
		$csvname = $csvname.'.csv';
		$fp = fopen($csvdir.$csvname, 'w+');
				
		
		$carts = $this->Cart_model->all($order['session_id']);
		
				$productname='';
				$customer = $this->Customer_model->identify($order['customer_id']);
				$item_no = 1;
				$total_quantity = 0;
				foreach($carts as $cart)
				{
					$total_quantity = $total_quantity + $cart['quantity'];
				}
				foreach($carts as $cart)
				{
					$product = $this->Product_model->identify($cart['product_id']);
		            fputcsv($fp,array("7-Eleven",$order['id'],date('Y-m-d',strtotime($order['order_time'])),"DirectToStore","AUD","en","7Eleven_GLN",$customer['storeno'],$customer['franchisee'],$customer['address'],$customer['suburb'],$customer['state'],$customer['postcode'],"EPE_GLN","EPE","EPE International","2A Robert Street","Collingwood","VIC","3066",$customer['storeno'],$customer['address'],$customer['suburb'],$customer['state'],$customer['postcode'],$order['message'],$item_no,$product['id'],"product barcode",$product['long_desc'],$cart['quantity'],$cart['price'],"EA",$order['message'],$total_quantity,$order['total']));
		            $item_no++;
				}
			
        	fclose($fp);
			$this->Order_model->update($order['id'],array('exported' => 1));
	  }
	
	}
}
?>